package com.hb.trade.server.project.calibration.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hb.core.pojo.enums.DeployStatusEnum;
import com.hb.core.pojo.enums.NoticeNatureEnum;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.calibration.dto.BidWinResultDTO;
import com.hb.core.pojo.project.calibration.dto.BidWinResultSupplyDTO;
import com.hb.core.pojo.project.calibration.dto.PortalBidWinDTO;
import com.hb.core.pojo.project.calibration.entity.BidWinResult;
import com.hb.core.pojo.project.calibration.entity.BidWinResultSupply;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.trade.server.project.calibration.manager.BidWinResultManager;
import com.hb.trade.server.project.calibration.service.BidWinResultService;
import com.hb.trade.server.project.calibration.service.BidWinResultSupplyService;
import com.hb.trade.server.project.deal.service.BidCandidateService;
import com.hb.trade.server.project.deal.service.BidCandidateSupplierService;
import com.hb.trade.server.project.proj.service.ProjectService;
import com.hb.trade.server.project.section.manager.BidSectionManager;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.IdUtil;
import org.fzzn.core.util.MsgUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 中标结果公示/公告表 前端控制器
 * </p>
 *
 * @author zhongdl
 * @since 2021-12-18
 */
@RestController
public class BidWinResultController {

    protected final BidWinResultService bidWinResultService;
    protected final BidSectionService bidSectionService;
    protected final BidWinResultSupplyService bidWinResultSupplyService;
    protected final BidCandidateSupplierService bidCandidateSupplierService;
    protected final BidCandidateService bidCandidateService;
    protected final ProjectService projectService;

    public BidWinResultController(BidWinResultService bidWinResultService,
                                  BidSectionService bidSectionService,
                                  BidWinResultSupplyService bidWinResultSupplyService,
                                  BidCandidateSupplierService bidCandidateSupplierService,
                                  BidCandidateService bidCandidateService,
                                  ProjectService projectService) {
        this.bidWinResultService = bidWinResultService;
        this.bidSectionService = bidSectionService;
        this.bidWinResultSupplyService = bidWinResultSupplyService;
        this.bidCandidateSupplierService = bidCandidateSupplierService;
        this.bidCandidateService = bidCandidateService;
        this.projectService = projectService;
    }

    /**
     *
     * @Description: 查询中标结果公告编辑信息和详情信息
     * @Author: zhongdl
     * @Date:2021/12/18 14:21
     * @param bidWinResult:
     * @return: {@link Message< BidWinResultDTO> }
     **/
    @PostMapping("/bidWinResult/bidWinResultInfoDetail")
    public Message<BidWinResultDTO> bidWinResultInfoDetail(@RequestBody BidWinResultDTO bidWinResult) {
        //查询中标结果信息
        BidWinResult bidWinResultDB = bidWinResultService.getById(bidWinResult.getId());
        if (bidWinResultDB == null) {
            return MsgUtil.fail("中标结果公示信息不存在 请重新刷新进入");
        }
        bidWinResultDB.to(bidWinResult);
        //根据中标结果公告id多个标段的
        List<BidWinResultSupplyDTO> successfulNoticeSupplies = bidWinResultSupplyService.listSuccessfulNoticeSupply(bidWinResult.getId());
        bidWinResult.setSuccessfulNoticeSupplyList(successfulNoticeSupplies);
        if (CollUtil.isEmpty(successfulNoticeSupplies)) {
            return MsgUtil.success(bidWinResult);
        }
        List<Long> bidSectionIdList = successfulNoticeSupplies.stream().map(BidWinResultSupplyDTO::getSectionId).collect(Collectors.toList());
        List<BidSection> bidSections = bidSectionService.findBidSectionList(bidSectionIdList);
        bidWinResult.setBidSectionList(bidSections);
        return MsgUtil.success(bidWinResult);
    }

    /**
     *
     * @Description: 保存中标结果公示
     * @Author: zhongdl
     * @Date:2021/12/18 15:52
     * @param bidWinResult:
     * @return: {@link Message< Boolean> }
     **/
    @Transactional
    @PostMapping("/bidWinResult/saveBidWinResult")
    public Message<BidWinResultDTO> saveBidWinResult(@RequestBody BidWinResultDTO bidWinResult) {
        String msg = bidWinResult.paramsValid("noticeTitle,medium,pushFlag,bidderName,bidderAmount,bidder");
        if (StrUtil.isNotEmpty(msg)) {
            return MsgUtil.fail(msg);
        }
        //判断一下否在变更
        Boolean releaseFlag = bidWinResultService.releaseFlagById(bidWinResult.getId());
        if (releaseFlag) {
            bidWinResult.setParentId(bidWinResult.getId());
            bidWinResult.setId(0L);
        }
        //id为空则为新增或者id为0 否则为更新
        Boolean supplyByWinResultBoolean = false;
        if (bidWinResult.getId() == null || Long.valueOf(0L).equals(bidWinResult.getId())) {
            bidWinResult.buildBaseData(1);
            bidWinResult.setDeployStatus(DeployStatusEnum.UN_DEPLOYED.getCode());
        } else {
            bidWinResult.buildBaseData(2);
            supplyByWinResultBoolean = bidWinResultSupplyService.deleteSuccessfulNoticeSupplyByWinResultId(bidWinResult.getId());
        }

        if (supplyByWinResultBoolean) {
            List<Long> sectionIdList = bidWinResult.getSuccessfulNoticeSupplyList().stream().map(BidWinResultSupply::getSectionId).collect(Collectors.toList());
            // 查询该标段是否存在被其他公告保存
            List<BidWinResultSupply> resultSupplyList = this.bidWinResultSupplyService.selectResultSupplyBySectionIdList(sectionIdList);
            if (!CollUtil.isEmpty(resultSupplyList)) {
                // 存在被其他结果公示绑定标段 手动回滚删除
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return MsgUtil.fail("选择标段中，存在被其他结果公示绑定标段");
            }
        }
        boolean save = bidWinResultService.saveOrUpdate(bidWinResult);
        Long id = bidWinResult.getId();
        //删除中标人
        //保存中标人列表
        List<BidWinResultSupply> saveResultSupplyList = bidWinResult.to(BidWinResultManager.class).listConversionSuccessful();
        // TODO key 冲突  前端把sectionID当ID穿过来了 后期需要优化
        for (BidWinResultSupply bidWinResultSupply : saveResultSupplyList) {
            bidWinResultSupply.setId(IdUtil.getId());
        }
        bidWinResultSupplyService.saveBatch(saveResultSupplyList);
        return MsgUtil.success(bidWinResult);
    }

    /**
     *
     * @Description: 发布中标结果公告
     * @Author: zhongdl
     * @Date:2021/12/18 17:12
     * @param bidWinResultDTO:
     * @return: {@link Message< Boolean> }
     **/
    @PostMapping("/bidWinResult/releaseBidWinResult")
    public Message<Boolean> releaseBidWinResult(@RequestBody BidWinResultDTO bidWinResultDTO) {
        BidWinResult bidWinResult = bidWinResultService.getById(bidWinResultDTO.getId());
        if (CollUtil.isEmpty(bidWinResult.getSignFile())) {
            return MsgUtil.fail("文件还未签章,签章之后再发布");
        }
        Boolean flag = bidWinResultService.updateDeployStatusById(bidWinResultDTO.getId(), DeployStatusEnum.DEPLOYED);
        //更新标段状态
        List<BidWinResultSupplyDTO> bidWinResultSupplyDTOList = bidWinResultSupplyService.listSuccessfulNoticeSupply(bidWinResult.getId());
        if (CollUtil.isNotEmpty(bidWinResultSupplyDTOList)) {
            for (BidWinResultSupplyDTO bidWinResultSupplyDTO : bidWinResultSupplyDTOList) {
                BidSection bidSection = bidSectionService.getById(bidWinResultSupplyDTO.getSectionId());
                if (bidSection == null) {
                    continue;
                }
                bidSection.to(BidSectionManager.class).refreshBidSection();
            }
        }
        return MsgUtil.success(flag);
    }

    /**
     *
     * @Description: 根据项目id分页查询中标结果公告列表
     * @Author: zhongdl
     * @Date:2021/12/20 9:26
     * @param bidWinResultDTO:
     * @return: {@link Message< PageResult< BidWinResultDTO>> }
     **/
    @PostMapping("/bidWinResult/pageBidWinResult")
    public Message<PageResult<BidWinResultDTO>> pageBidWinResult(@RequestBody BidWinResultDTO bidWinResultDTO) {
        PageResult<BidWinResultDTO> pageResult = bidWinResultService.pageBidWinResult(bidWinResultDTO);
        return MsgUtil.success(pageResult);
    }

    /**
     *
     * @Description: 根据标段id分页查询已经发布的中标结果公告列表
     * @Author: zhongdl
     * @Date:2021/12/20 9:26
     * @param bidWinResultDTO:
     * @return: {@link Message< PageResult< BidWinResultDTO>> }
     **/
    @PostMapping("/bidWinResult/pageBidWinResultBySectionId")
    public Message<PageResult<BidWinResultDTO>> pageBidWinResultBySectionId(@RequestBody BidWinResultDTO bidWinResultDTO) {
        PageResult<BidWinResultDTO> pageResult = bidWinResultService.pageBidWinResultBySectionId(bidWinResultDTO);
        return MsgUtil.success(pageResult);
    }

    /**
     *
     * @Description: 根据中标结果id更新公告内容
     * @Author: zhongdl
     * @Date:2021/12/20 11:09
     * @param bidWinResultDTO:
     * @return: {@link Message< Boolean> }
     **/
    @PostMapping("/bidWinResult/updateNoticeContent")
    public Message<BidWinResultDTO> updateNoticeContent(@RequestBody BidWinResultDTO bidWinResultDTO) {
        Long id = bidWinResultDTO.getId();
        //查询库里的中标结果公告去更新
        BidWinResult bidWinResult = bidWinResultService.getById(id);
        bidWinResultDTO.to(bidWinResult);
        boolean update = bidWinResultService.updateById(bidWinResult);
        return MsgUtil.success(bidWinResultDTO);
    }

    /**
     *
     * @Description: 新建中标结果公告时返回项目信息
     * @Author: zhongdl
     * @Date:2022/1/5 9:50
     * @param bidWinResult:
     * @return: {@link Message< BidWinResultDTO> }
     **/
    @PostMapping("/bidWinResult/initWinResultInfo")
    public Message<BidWinResultDTO> initWinResultInfo(@RequestBody BidWinResultDTO bidWinResult) {
        AbstractProject project = projectService.getByPrimaryKey(bidWinResult.getProjectId());
        if (project == null) {
            return MsgUtil.fail("项目信息不存在,请重新进入");
        }
        //首次公告
        bidWinResult.setNoticeNature(NoticeNatureEnum.FIRST.getCode());
        project.to(bidWinResult);
        //设置公告表题
        bidWinResult.setNoticeTitle(bidWinResult.getProjectName() + "中标结果公示");
        return MsgUtil.success(bidWinResult);
    }

    /**
     *
     * @Description: 根据项目id查询 未新建中标结果公告的标段 并且已经评标结果状态的
     * @Author: zhongdl
     * @Date:2022/1/5 13:53
     * @param bidWinResult:
     * @return: {@link Message< List< BidWinResultDTO>> }
     **/
    @PostMapping("/bidWinResult/pageNotSelectBidSection")
    public Message<PageResult<BidWinResultDTO>> listNotSelectBidSection(@RequestBody BidWinResultDTO bidWinResult) {
        PageResult<BidWinResultDTO> bidWinResultDTOS = bidWinResultService.pageNotSelectBidSection(bidWinResult);
        return MsgUtil.success(bidWinResultDTOS);
    }

    /**
     *
     * @Description: 查询中标结果公示包含的标段信息
     * @Author: zhongdl
     * @Date:2022/1/5 17:10
     * @param successfulNoticeSupply:
     * @return: {@link Message< PageResult<  BidWinResultSupplyDTO >> }
     **/
    @PostMapping("/bidWinResult/pageIncludeBidSection")
    public Message<PageResult<BidWinResultSupplyDTO>> pageIncludeBidSection(@RequestBody BidWinResultSupplyDTO successfulNoticeSupply) {
        PageResult<BidWinResultSupplyDTO> pageResult = bidWinResultSupplyService.pageIncludeBidSection(successfulNoticeSupply);
        return MsgUtil.success(pageResult);
    }

    /**
     * 门户网站查询对应的结果公示
     * @param portalBidWinDTO
     * @return
     * @Author: LJS
     * @Date:2022-2-18 11:34:39
     */
    @PostMapping("/bidWinResult/pageBidWinPortal")
    public Message<PageResult<PortalBidWinDTO>> pageBidWinPortal(@RequestBody PortalBidWinDTO portalBidWinDTO) {
        PageResult<PortalBidWinDTO> pageResult = bidWinResultService.pageBidWinPortal(portalBidWinDTO);
        for (PortalBidWinDTO bidWinDTO : pageResult.getRecords()) {
            // 日期格式化
            if (bidWinDTO.getCreateTime() != null) {
                bidWinDTO.setPublishDate(bidWinDTO.getCreateTime());
            }
        }
        return MsgUtil.success(pageResult);
    }

    /**
     *门户网站查询对应的公告详情
     * @param portalBidWinDTO
     * @return
     * @Author: LJS
     * @Date:2022-2-18 11:34:39
     */
    @PostMapping("/bidWinResult/detailBidWinPortal")
    public Message<PortalBidWinDTO> detailBidWinPortal(@RequestBody PortalBidWinDTO portalBidWinDTO) {
        if (portalBidWinDTO == null || portalBidWinDTO.getId() == null) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM_TYPE.msg());
        }
        PortalBidWinDTO result = bidWinResultService.detailBidWinPortal(portalBidWinDTO);
        if (result != null) {
            LambdaQueryWrapper<BidWinResultSupply> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BidWinResultSupply::getWinResultId, result.getId());
            wrapper.last("limit 1");
            BidWinResultSupply bidWinResultSupply = bidWinResultSupplyService.getOne(wrapper);
            if (bidWinResultSupply != null) {
                portalBidWinDTO.setSectionId(bidWinResultSupply.getSectionId().toString());
            }
            BidWinResult bidWinResult = result.to(BidWinResult.class);
            Integer num = bidWinResult.getClickCount();
            if (num == null) {
                num = 0;
            }
            bidWinResult.setClickCount(num + 1);
            result.setClickCount(num + 1);
            bidWinResultService.updateById(bidWinResult);
            if (result.getCreateTime() != null) {
                result.setPublishDate(result.getCreateTime());
            }
        }
        return MsgUtil.success(result);
    }

    /**
     *
     * @Description: 查询所有需要推送的中标结果公告
     * @Author: zhongdl
     * @Date:2022/2/24 13:56
     * @param bidWinResultDTO:
     * @return: {@link Message< PageResult< BidWinResultSupplyDTO>> }
     **/
    @PostMapping("/bidWinResult/listPushBidWinResultSupply")
    public Message<List<BidWinResultDTO>> listPushBidWinResultSupply(@RequestBody BidWinResultDTO bidWinResultDTO) {
        List<BidWinResultDTO> list = bidWinResultService.listPushBidWinResult();
        if (CollUtil.isEmpty(list)) {
            return MsgUtil.success(list);
        }
        for (BidWinResultDTO bidWinResult : list) {
            List<BidWinResultSupplyDTO> bidWinResultSupplyDTOS = bidWinResultSupplyService.listSuccessfulNoticeSupply(bidWinResult.getId());
            bidWinResult.setSuccessfulNoticeSupplyList(bidWinResultSupplyDTOS);
            if (CollUtil.isEmpty(bidWinResultSupplyDTOS)) {
                continue;
            }
            BidWinResultSupply bidWinResultSupply = bidWinResultSupplyDTOS.get(0);
            if (bidWinResultSupply == null) {
                continue;
            }
            bidWinResult.setBidWinResultSupply(bidWinResultSupply.to(BidWinResultSupplyDTO.class));
        }
        return MsgUtil.success(list);
    }

    /**
     * 查询当前企业是否中标
     * @author tian
     * @date 2022-2-28 18:18
     * @param bidWinResultDTO
     * @return org.fzzn.core.model.msg.Message<com.hb.core.pojo.project.calibration.dto.BidWinResultSupplyDTO>
     */
    @PostMapping("/bidWinResult/findWinResultSupplyBySectionIdAndOrgId")
    public Message<Boolean> findWinResultSupplyBySectionIdAndOrgId(@RequestBody BidWinResultDTO bidWinResultDTO) {
        Boolean flag = bidWinResultSupplyService.getWinResultSupplyBySectionId(bidWinResultDTO.getSectionId(), bidWinResultDTO.getOrgId());
        return MsgUtil.success(flag);
    }
}
